<template>
  <div class="client-container">
    <div style="margin-bottom: 20px; display: flex; align-items: center;">
      <el-button-group>
        <el-button type="primary" :plain="currentTab !== 'all'" @click="switchTab('all')">全部</el-button>
        <el-button type="primary" :plain="currentTab !== 'waitPass'" @click="switchTab('waitPass')">待审核</el-button>
      </el-button-group>
      <el-input v-if="currentTab !== 'waitPass'" v-model="searchQuery" placeholder="请输入客户名称" style="width: 200px; margin-right: 10px; margin-left: 10px;"></el-input>
      <el-button v-if="currentTab !== 'waitPass'" type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
      <el-button type="danger" @click="handleForceLogout" style="margin-left: auto;">强制下线</el-button>
    </div>
    <el-dialog v-model="editDialogVisible" title="编辑客户信息" width="30%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="客户账号">
          <el-input v-model="editForm.clientName" />
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="editForm.company" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }]">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="editForm.realname" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="customerId" label="客户ID" width="180" />
      <el-table-column prop="clientName" label="客户名称" width="180" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="realname" label="地址" />
      <el-table-column prop="company" label="公司名称" />
      <el-table-column prop="accountStatus" label="状态" width="100" :formatter="formatStatus"/>
      <el-table-column prop="lastloginAt" label="最后登录时间" width="100"/>
      <el-table-column prop="lastloginIp" label="最后登录ip" width="100"/>
      <el-table-column prop="createAt" label="创建时间" />
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row.customerId)">删除</el-button>
        <el-button :type="scope.row.accountStatus === 0 ? 'warning' : 'success'" size="small" @click="handleChangeStatus(scope.row)">{{ scope.row.accountStatus === 0 ? '禁用' : '启用' }}</el-button>
      </template>
    </el-table-column>
    </el-table>
    
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, prev, pager, next, jumper">
    </el-pagination>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import querystring from 'querystring';
import { ElMessage, ElMessageBox } from 'element-plus';

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const editForm = ref({})
const editDialogVisible = ref(false)
const searchQuery = ref('')
const currentTab = ref('all')

const switchTab = async (tab) => {
  currentTab.value = tab
  if (tab === 'waitPass') {
    await fetchWaitPassClients()
  } else {
    await fetchClients()
  }
}

const fetchWaitPassClients = async () => {
  try {
    const response = await axios.get("/api/admin/client/waitPass", {
      params: {
        pageNo: currentPage.value
      }
    })
    tableData.value = response.data.data.list
    totalCount.value = response.data.data.totalCount
    pageSize.value = response.data.data.pageSize
  } catch (error) {
    console.error('获取待审核客户列表失败:', error)
    tableData.value = []
  }
}

const fetchClients = async () => {
  try {
    const response = await axios.get("/api/admin/client", {
      params: {
        pageNo: currentPage.value
      }
    })
    tableData.value = response.data.data.list
    totalCount.value = response.data.data.totalCount
    pageSize.value = response.data.data.pageSize
  } catch (error) {
    console.error('获取客户列表失败:', error)
    tableData.value = []
  }
}

const formatStatus = (row) => {
  return row.accountStatus === 0 ? '正常' : '禁用';
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchClients()
}

const handleChangeStatus = async (row) => {
  try {
    const status = row.accountStatus === 0 ? 1 : 0;
    await axios.post('/api/admin/client/changeStatus', querystring.stringify({
      customerName: row.clientName,
      status: status
    }));
    ElMessage.success('状态更新成功');
    fetchClients();
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  }
}

const handleDelete = async (customerId) => {
  try {
    await axios.post('/api/admin/client/delete', querystring.stringify({ customerId: customerId }));
    ElMessage.success('删除成功');
    fetchClients();
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
}

const handleEdit = (row) => {
   editForm.value = {
     clientName: row.clientName,
     company: row.company,
     phone: row.phone,
     realname: row.realname,
     password: '',
     customerId: row.customerId
   };
  
   editDialogVisible.value = true;
 }

 const handleForceLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要强制该用户下线吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await axios.get('/api/admin/client/putdown');
    ElMessage.success('强制下线成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('强制下线失败:', error);
      ElMessage.error('强制下线失败');
    }
  }
};

const handleSearch = async () => {
  try {
    const response = await axios.get("/api/admin/client/search", {
      params: {
        CilentFuzzyName: searchQuery.value,
        pageNo: currentPage.value
      }
    })
    tableData.value = response.data.data.list
    totalCount.value = response.data.data.totalCount
    pageSize.value = response.data.data.pageSize
  } catch (error) {
    console.error('搜索失败:', error)
    tableData.value = []
  }
}

const saveEdit = async () => {
   try {
     await axios.post('/api/admin/client/update', editForm.value ,{
      headers: {
        'Content-Type': 'application/json'
      }
    });
     ElMessage.success('修改成功');
     editDialogVisible.value = false;
     fetchClients();
   } catch (error) {
     console.error('修改失败:', error);
     ElMessage.error('修改失败');
   }
 }

onMounted(() => {
  fetchClients()
})
</script>

<style scoped>
.client-container {
  padding: 20px;
}
.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>